<template>
  <div class="app-container">
    <!-- 搜索 -->
    <el-card class="box-card">
      <el-row type="flex" align="middle">
        <el-col :span="12">
          <div class="grid-content bg-purple search">
            <el-form ref="query" :model="query" label-width="100px">
              <el-form-item style="margin-bottom:0px" label="名称">
                <i slot="label" class="el-icon-search" style="font-size:20px"></i>
                <el-input style="width:360px" v-model="query.keywords" placeholder="请输入活动名称"></el-input>
              </el-form-item>
            </el-form>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="grid-content bg-purple-light" style="text-align:right">
            <el-button type="primary" @click="queryAsk">查询</el-button>
            <el-button @click="queryReset">重置</el-button>
          </div>
        </el-col>
      </el-row>
    </el-card>
    <!-- 表格 -->
    <el-card class="box-card">
      <el-button type="primary" style="margin-bottom:20px" @click="addList">添加</el-button>
      <el-table
        :data="tableData"
        :header-cell-style="{background:'#eee'}"
        border
        style="width: 100%;margin-bottom: 20px;"
        v-loading="loading"
      >
        <!-- <el-table-column align="center" type="index" width="50" label="序号"></el-table-column> -->
        <el-table-column align="center" prop="id" width="120" label="设置所用id"></el-table-column>

        <el-table-column align="center" label="封面图">
          <template slot-scope="scope">
            <el-popover placement="top-start" title trigger="hover">
              <img :src="scope.row.img" alt style="max-width:150px" />
              <!-- <el-avatar shape="square" :size="150" fit="cover" :src="scope.row.img"></el-avatar> -->
              <el-avatar
                slot="reference"
                shape="square"
                :size="50"
                fit="scale-down"
                :src="scope.row.img"
              ></el-avatar>
              <!-- <img
                slot="reference"
                :src="scope.row.img"
                style="width: 60px;height: 60px"
              />-->
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="title" label="标题"></el-table-column>
        <el-table-column align="center" label="是否显示">
          <template slot-scope="scope">
            <div v-if="scope.row.is_show==1">是</div>
            <div v-if="scope.row.is_show==0">否</div>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="start_time" label="开始时间"></el-table-column>
        <el-table-column align="center" prop="end_time" label="结束时间"></el-table-column>
        <el-table-column align="center" fixed="right" label="操作" width="150">
          <template slot-scope="scope">
            <el-button @click="handleEdite(scope.row)" type="text" size="small">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="text-align:right">
        <el-pagination
          background
          layout="prev, pager, next"
          :current-page="currentPage"
          :total="total"
          @current-change="currentChange"
        ></el-pagination>
      </div>
    </el-card>

    <el-drawer :title="title" :visible.sync="drawer" :before-close="handleClose">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="标题" prop="title">
          <el-input style="width:360px" v-model="form.title"></el-input>
        </el-form-item>
        <el-form-item label="上传封片图片" prop="img">
          <el-upload
            class="avatar-uploader"
            action="https://upload-z0.qiniup.com/"
            :data="postData"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="是否展示" prop="is_show">
          <el-select style="width:360px" v-model="form.is_show" placeholder="请选择是否展示">
            <el-option label="是" value="1"></el-option>
            <el-option label="否" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="start_time">
          <el-date-picker
            style="width:360px"
            v-model="form.start_time"
            type="datetime"
            placeholder="选择开始日期时间"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="end_time">
          <el-date-picker
            style="width:360px"
            v-model="form.end_time"
            type="datetime"
            placeholder="选择结束日期时间"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select style="width:360px" v-model="form.type" placeholder="请选择类型">
            <el-option label="富文本" value="1"></el-option>
            <el-option label="盲盒" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="内容" prop="details" v-if="form.type==1">
          <tinymce v-model="form.details" :height="300" />
        </el-form-item>
        <el-form-item label="盲盒" prop="box_id" v-if="form.type==2">
          <el-button type="primary" style="margin-right:10px" @click="chooseBox">选择盲盒</el-button>
          <el-tag type="success" v-if="sendForm.box_id">{{chooseBoxInfo}}</el-tag>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">确定</el-button>
          <el-button @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>

    <!-- 选择盲盒-->
    <el-dialog
      title="选择商品"
      :visible.sync="boxdialogVisible"
      width="60%"
      :before-close="boxhandleClose"
    >
      <!-- 搜索 -->
      <el-card class="box-card">
        <div class="query-card">
          <!-- <el-row type="flex" align="middle">
          <el-col :span="12">-->
          <div class="grid-content bg-purple search">
            <el-form ref="boxquery" :model="query" label-width="100px">
              <el-form-item style="margin-bottom:0px" label="名称">
                <i slot="label" class="el-icon-search" style="font-size:20px"></i>
                <el-input style="width:360px" v-model="boxquery.keywords" placeholder="请输入盲盒名称搜索"></el-input>
              </el-form-item>
              <el-form-item style="margin-bottom:0px" label="分类">
                <el-select style="width:360px" v-model="boxquery.type" placeholder="请选择分类">
                  <el-option label="全部" value="0"></el-option>
                  <el-option label="天选之人" value="1"></el-option>
                  <el-option label="无限盲盒" value="2"></el-option>
                </el-select>
              </el-form-item>
            </el-form>
          </div>
          <!-- </el-col> -->
          <!-- <el-col :span="12"> -->
          <div class="grid-content bg-purple-light">
            <el-button type="primary" @click="boxqueryAsk">查询</el-button>
            <el-button @click="boxqueryReset">重置</el-button>
          </div>
          <!-- </el-col>
          </el-row>-->
        </div>
      </el-card>
      <el-card class="box-card">
        <el-table
          ref="multipleTable"
          :data="boxtableData"
          tooltip-effect="dark"
          border
          style="width: 100%;margin-bottom: 20px;"
          :header-cell-style="{background:'#eee'}"
          v-loading="boxloading"
          @row-click="handleSelectionChange"
        >
          <el-table-column align="center" width="55">
            <template slot-scope="scope">
              <el-radio v-model="sendForm.box_id" :label="scope.row.id">{{""}}</el-radio>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="id" label="ID" width="55"></el-table-column>
          <el-table-column align="center" label="封面图片">
            <template slot-scope="scope">
              <el-popover placement="top-start" title trigger="hover">
                <img :src="scope.row.img" alt style="max-width:250px" />
                <!-- <el-avatar shape="square" :size="150" fit="cover" :src="scope.row.img"></el-avatar> -->
                <el-avatar
                  slot="reference"
                  shape="square"
                  :size="50"
                  fit="scale-down"
                  :src="scope.row.img"
                ></el-avatar>
                <!-- <img
                slot="reference"
                :src="scope.row.img"
                style="width: 60px;height: 60px"
                />-->
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="name" label="盲盒名称"></el-table-column>
          <el-table-column align="center" label="类型">
            <template slot-scope="scope">
              <div v-if="scope.row.type==1">天选之人</div>
              <div v-if="scope.row.type==2">无限盲盒</div>
              <div></div>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="price" label="单价"></el-table-column>
          <el-table-column align="center" prop="id" label="是否预售">
            <template slot-scope="scope">
              <div v-if="scope.row.is_ys==1">是</div>
              <div v-if="scope.row.is_ys==0">否</div>
            </template>
          </el-table-column>
        </el-table>

        <div style="text-align:right">
          <el-pagination
            background
            layout="prev, pager, next"
            :current-page="boxcurrentPage"
            :total="boxtotal"
            @current-change="boxcurrentChange"
          ></el-pagination>
        </div>
      </el-card>
      <div style="text-align:right;margin-top:20px">
        <el-button type="primary" @click="boxAdd">确定</el-button>
        <el-button @click="boxdialogVisible=false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Tinymce from '@/components/Tinymce'
import { acivityList, addAcivityList, editAcivityList } from '@/api/system'
import { parseTime } from '@/utils/index'
import { getToken } from '@/api/qiniu'
import { blinboxList } from '@/api/blindbox'

export default {
  name: 'ActivityCenter',
  components: { Tinymce },
  data() {
    return {
      // 分页数据
      total: 0,
      currentPage: 1,
      pageSize: 10,
      //input
      query: {
        keywords: ''
      },
      tableData: [],
      loading: false,
      drawer: false,
      title: '添加',
      form: {
        title: '',
        img: '',
        is_show: '',
        start_time: '',
        type: '',
        box_id: '',
        end_time: '',
        details: ''
      },
      rules: {
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        img: [{ required: true, message: '请选择图片', trigger: 'blur' }],
        is_show: [
          { required: true, message: '请选择是否展示', trigger: 'blur' }
        ],
        start_time: [
          { required: true, message: '请选择开始时间', trigger: 'blur' }
        ],
        type: [{ required: true, message: '请选择类型', trigger: 'blur' }],
        box_id: [{ required: true, message: '请选择盲盒', trigger: 'blur' }],
        end_time: [
          { required: true, message: '请选择结束时间', trigger: 'blur' }
        ],
        details: [{ required: true, message: '请输入内容', trigger: 'blur' }]
      },
      // 上传图片
      url: '',
      imageUrl: '',
      postData: {
        token: ''
      },
      boxdialogVisible: false,
      // 盲盒数据
      boxtotal: 0,
      boxcurrentPage: 1,
      boxpageSize: 10,
      //query
      boxquery: {
        keywords: '',
        type: '0'
      },
      boxtableData: [],
      selectList: [],
      boxloading: false,
      sendForm: {
        box_id: ''
      },
      chooseBoxInfo: ''
    }
  },
  mounted() {
    this.getToken()
    this.getList()
  },
  methods: {
    async getList() {
      const res = await acivityList({
        page: this.currentPage,
        limit: this.pageSize,
        keywords: this.query.keywords
      })
      console.log(res)
      this.tableData = res.data
      this.total = res.count
      this.tableData.forEach((item) => {
        if (item.start_time == 0) {
          item.start_time = '-'
        } else {
          item.start_time = parseTime(
            item.start_time,
            '{y}-{m}-{d} {h}:{i}:{s}'
          )
        }
        if (item.end_time == 0) {
          item.end_time = '-'
        } else {
          item.end_time = parseTime(item.end_time, '{y}-{m}-{d} {h}:{i}:{s}')
        }
      })
    },

    queryAsk() {
      this.currentPage = 1
      this.getList()
    },
    //重置
    queryReset() {
      this.resetForm('query')
      this.total = 0
      this.currentPage = 1
      this.pageSize = 10
      this.query.keywords = ''
      this.getList()
    },
    //分页改变
    currentChange(current) {
      this.currentPage = current
      this.getList()
    },
    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    //添加
    addList() {
      this.title = '添加'
      this.drawer = true
    },
    // 上传图片
    async getToken() {
      const res = await getToken()
      this.postData.token = res.data.uptoken
      this.url = res.data.domain
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = this.url + res.key
      this.form.img = this.imageUrl
    },
    beforeAvatarUpload(file) {
      //   const isJPG = file.type === "image/jpeg";
      //   if (!isJPG) {
      //     this.$message.error("上传头像图片只能是 JPG 格式!");
      //   }
      const isLt1M = file.size / 1024 / 1024 < 1

      if (!isLt1M) {
        this.$message.error('上传头像图片大小不能超过 1MB!')
        return
      }
    },
    handleClose(done) {
      this.resetForm('form')
      const form = {
        id: '',
        title: '',
        img: '',
        is_show: '',
        start_time: '',
        end_time: '',
        details: ''
      }
      this.imageUrl = ''
      this.form = form
      done()
    },
    handleEdite(row) {
      this.title = '编辑'
      this.drawer = true
      this.form.id = row.id
      this.form.title = row.title
      this.form.img = row.img
      this.imageUrl = row.img
      this.form.is_show = row.is_show
      this.form.start_time = row.start_time
      this.form.end_time = row.end_time
      this.form.details = row.details
      this.form.box_id = row.box_id
      this.sendForm.box_id = row.box_id
      this.form.type = row.type
      this.chooseBoxInfo = row.box_name
    },
    onSubmit() {
      this.form.start_time = parseTime(this.form.start_time)
      this.form.end_time = parseTime(this.form.end_time)
      this.$refs['form'].validate(async (valid) => {
        if (valid) {
          if (this.title == '添加') {
            const res = await addAcivityList({ ...this.form })
            if (res.st === 1) {
              this.resetForm('form')
              const form = {
                title: '',
                img: '',
                is_show: '',
                start_time: '',
                end_time: '',
                details: ''
              }
              this.imageUrl = ''
              this.form = form
              this.getList()
              this.$message({
                message: '添加成功',
                type: 'success'
              })
              this.drawer = false
            } else {
              console.log(res)
              this.$message.error('添加失败')
            }
          } else {
            const res = await editAcivityList({ ...this.form })
            if (res.st === 1) {
              this.resetForm('form')
              const form = {
                id: '',
                title: '',
                img: '',
                is_show: '',
                start_time: '',
                end_time: '',
                details: ''
              }
              this.imageUrl = ''
              this.form = form
              this.getList()
              this.$message({
                message: '添加成功',
                type: 'success'
              })
              this.drawer = false
            } else {
              console.log(res)
              this.$message.error('添加失败')
            }
          }
        }
      })
    },
    cancel() {
      this.resetForm('form')
      const form = {
        id: '',
        title: '',
        img: '',
        is_show: '',
        start_time: '',
        end_time: '',
        details: ''
      }
      this.imageUrl = ''
      this.form = form
      this.drawer = false
    },

    // 选择盲盒
    chooseBox() {
      this.boxdialogVisible = true
      this.getBoxList()
    },
    boxhandleClose(done) {
      done()
    },
    // 盲盒列表
    async getBoxList() {
      this.boxloading = true
      const res = await blinboxList({
        page: this.boxcurrentPage,
        limit: this.boxpageSize,
        keywords: this.boxquery.keywords,
        type: this.boxquery.type,
        is_template: 0
      })
      console.log(res)
      this.boxloading = false
      this.boxtableData = res.data
      this.boxtotal = res.count
    },
    boxqueryAsk() {
      console.log(this.boxquery)
      this.boxcurrentPage = 1
      this.getBoxList()
    },
    boxqueryReset() {
      this.resetForm('boxquery')
      this.boxtotal = 0
      this.boxcurrentPage = 1
      this.boxpageSize = 10
      this.boxquery.keywords = ''
      this.boxquery.type = '0'
      this.getBoxList()
    },
    //盲盒分页改变
    boxcurrentChange(current) {
      this.boxcurrentPage = current
      this.getBoxList()
    },
    handleSelectionChange(val) {
      console.log(val)
      this.chooseBoxInfo = val.name
      this.sendForm.box_id = val.id
    },
    // 确认添加
    boxAdd() {
      this.form.box_id = this.sendForm.box_id
      this.boxdialogVisible = false
    }
  }
}
</script>

<style lang="scss" scoped>
.query-card {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  ::v-deep .el-form {
    display: flex;
  }
}
.box-card {
  margin-bottom: 20px;
}
.search {
  display: flex;
  align-items: center;
}
::v-deep .el-input--medium .el-input__inner {
  // width: 360px;
}
::v-deep .el-textarea__inner {
  width: 360px;
}
// ::v-deep .el-drawer.rtl {
//   width: 650px !important;
//   overflow: auto;
// }
::v-deep .el-drawer.rtl {
  padding-bottom: 20px;
  padding-right: 20px;
  width: 60% !important;
  overflow: auto;
}
// 上传图片
::v-deep .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>